package cn.jinjimi.app.main.dialog;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiiu.filter.util.UIUtil;
import com.facebook.drawee.drawable.ScalingUtils;
import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.domain.data.Cache;
import cn.jinjimi.app.poster.activity.PosterListActivity;
import cn.jinjimi.app.poster.bean.PosterInfo;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.poster.interfaces.IPosterLoadMore;
import cn.jinjimi.app.poster.interfaces.PosterDialogView;
import cn.jinjimi.app.poster.interfaces.PosterFragmentPopupView;
import cn.jinjimi.app.poster.presenter.PosterPresenter;
import cn.jinjimi.app.poster.presenter.SharePosterPresenter;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.bean.RouterConstants;
import cn.jinjimi.app.main.adapter.pagerAdapter.CyclePagerAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.FrescoImageView.FrescoImageView;
import cn.jinjimi.app.main.widget.RollViewPager.RollPagerView;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.baiiu.filter.util.UIUtil.dp;

/**
 * Created by lforxeverc on 16/9/22.
 */

public class SharePosterFragment extends BaseFragment
        implements PosterFragmentPopupView, View.OnClickListener, RollPagerView.onPagerChangeListener {

    public enum Style {
        Dialog, Normal
    }

    private Activity mContext;
    private ImageView ivPrevious, ivNext, ivRefresh, ivDownload, ivShare, ivClose, ivMore;
    private TextView tvRefresh, tvDownload, tvShare, tvClose;
    private RollPagerView vpPosters;
    private LinearLayout llFailTips;
    private RelativeLayout rlLoadingTips;
    private TextView tvPosition;
    private LinearLayout llActionBtns;
    private LinearLayout llClose, llMore;
    private SharePosterPresenter mPresenter;
    private RelativeLayout rlPosterContainer;
    private int mCurPosition, categoryCode, mLastPosition = -1;
    private Bitmap bitmap;
    private MyAdapter mAdapter;
    private IPosterLoadMore mLoadMoreListener;
    private int mTotal = 0;
    private boolean shouldRefresh = false;
    private PosterDialogView mRootDialogView;
    private Style style = Style.Dialog;
    private boolean isFirstComeIn = true;
    private CheckBox cbDisplayMark;

    private String source;
    private boolean isFirstDisplay = true;
    private AnalyTabHelper analyTabHelper = new AnalyTabHelper();

    public SharePosterFragment() {
    }

    public void setContext(Activity mContext) {
        this.mContext = mContext;
    }

    public void setLoadMoreListener(IPosterLoadMore mLoadMoreListener) {
        this.mLoadMoreListener = mLoadMoreListener;
    }

    public SharePosterFragment setInfos(int position, int total) {
        mCurPosition = position;
        mTotal = total;
        return this;
    }

    public SharePosterFragment setPosterDialogView(PosterDialogView dv) {
        mRootDialogView = dv;
        return this;
    }

    public SharePosterFragment setCategoryCode(int categoryCode) {
        this.categoryCode = categoryCode;
        if (mPresenter != null)
            mPresenter.setCategoryCode(categoryCode);
        return this;
    }

    public SharePosterFragment setStyle(Style style) {
        this.style = style;
        return this;
    }

    public SharePosterFragment setSource(String source) {
        this.source = source;
        return this;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.dialog_share_poster;
    }

    @Override
    protected void initial() {
        View rootView = findView();
        tvPosition = (TextView) rootView.findViewById(R.id.tv_position);
        ivPrevious = (ImageView) rootView.findViewById(R.id.iv_previous);
        ivNext = (ImageView) rootView.findViewById(R.id.iv_next);
        rlPosterContainer = (RelativeLayout) rootView.findViewById(R.id.rl_poster);
        rlLoadingTips = (RelativeLayout) rootView.findViewById(R.id.rl_loading);
        llFailTips = (LinearLayout) rootView.findViewById(R.id.ll_tips_container);
        vpPosters = (RollPagerView) rootView.findViewById(R.id.vp_posters);
        ivRefresh = (ImageView) rootView.findViewById(R.id.iv_refresh);
        ivDownload = (ImageView) rootView.findViewById(R.id.iv_download);
        ivShare = (ImageView) rootView.findViewById(R.id.iv_share);
        ivClose = (ImageView) rootView.findViewById(R.id.iv_close);
        llActionBtns = (LinearLayout) rootView.findViewById(R.id.ll_btns);
        tvRefresh = (TextView) rootView.findViewById(R.id.tv_refresh);
        tvDownload = (TextView) rootView.findViewById(R.id.tv_download);
        tvShare = (TextView) rootView.findViewById(R.id.tv_share);
        tvClose = (TextView) rootView.findViewById(R.id.tv_close);
        llClose = (LinearLayout) rootView.findViewById(R.id.ll_close);
        llMore = (LinearLayout) rootView.findViewById(R.id.ll_more);
        ivMore = (ImageView) rootView.findViewById(R.id.iv_more);
        cbDisplayMark = (CheckBox) rootView.findViewById(R.id.cb_display_mark);
        rootView.findViewById(R.id.rl_root).setOnClickListener(this);
        setNavView();
        //防止点击图片对话框消失
        rlPosterContainer.setOnClickListener(this);
        ivPrevious.setOnClickListener(this);
        ivNext.setOnClickListener(this);
        ivRefresh.setOnClickListener(this);
        ivDownload.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        ivMore.setOnClickListener(this);

        initStyle();

        mAdapter = new MyAdapter();
        List<Integer> mBlankFill = new ArrayList<>();
        mBlankFill.addAll(Collections.nCopies(mTotal, 0));
        vpPosters.setSupportCycle(false);
        mAdapter.setItems(mBlankFill);
        vpPosters.setAdapter(mAdapter);
        vpPosters.setOnPagerChangeListener(this);
        vpPosters.setHintViewVisibility(false);
        mPresenter = new SharePosterPresenter(mContext, this);
        mPresenter.setCategoryCode(categoryCode);
        isFirstDisplay = true;
        if (mCurPosition == 0) {
            onPageSelected(mCurPosition);
        } else {
            vpPosters.setCurrentItem(mCurPosition);
        }
        //稍微延迟，onPageSelected被调了两次
        vpPosters.postDelayed(new Runnable() {
            @Override
            public void run() {
                isFirstDisplay = false;
            }
        }, 50);
        vpPosters.setAutoScroll(false);
        setPositionView();

        cbDisplayMark.setChecked(mPresenter.isDisplayMark());
        cbDisplayMark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPresenter.setDisplayMark(isChecked);
                ivRefresh.callOnClick();
            }
        });
    }

    @Override
    public void showLoading() {
        setBtnStatus(false);
        llFailTips.setVisibility(View.GONE);
        rlLoadingTips.setVisibility(View.VISIBLE);
    }

    @Override
    public void loadFail(int position) {
        if (position != mCurPosition) return;
        setBtnStatus(false);
        llFailTips.setVisibility(View.VISIBLE);
        rlLoadingTips.setVisibility(View.GONE);
    }

    @Override
    public void loadSuccess(int realPosition, Bitmap bm) {
        if (mContext == null || realPosition != mCurPosition)
            return;
        if (bm == null || bm.isRecycled()) {
            llFailTips.setVisibility(View.VISIBLE);
            setBtnStatus(false);
            return;
        }
        bitmap = bm;
        llFailTips.setVisibility(View.GONE);
        rlLoadingTips.setVisibility(View.GONE);
        mAdapter.setCurrentViewBitmap(realPosition, Style.Normal == style ? addBorder(bm) : bm);
        rlPosterContainer.setBackgroundColor(Color.TRANSPARENT);
        setBtnStatus(true);
    }

    private Bitmap addBorder(Bitmap bm) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        int borderSize = 1;
        Bitmap bmpWithBorder = Bitmap.createBitmap(width + borderSize * 2, height + borderSize * 2, bm.getConfig());
        Canvas canvas = new Canvas(bmpWithBorder);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bm, borderSize, borderSize, null);
        return bmpWithBorder;
    }


    @Override
    public void dismissSelf() {
        if (style == Style.Dialog && mRootDialogView != null)
            mRootDialogView.dismissDialog();
    }

    @Override
    public void updatePosterInfo(PosterInfo info, int position) {
        if (mLoadMoreListener != null)
            mLoadMoreListener.updatePostInfo(info, position);
    }

    @Override
    public void showThumbnailUrl(PosterInfo info, int position) {
        mAdapter.loadDefaultView(position, info.thumbnailUrl);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_previous:
                mCurPosition--;
                vpPosters.previous();
                break;

            case R.id.iv_next:
                mCurPosition++;
                vpPosters.next();
                break;

            case R.id.iv_refresh:
                shouldRefresh = true;
                loadDataWithPosition(mCurPosition);
                break;

            case R.id.iv_share:
                //从后台回来后有可能bitmap被回收
                if (bitmap == null || bitmap.isRecycled()) {
                    loadDataWithPosition(mCurPosition);
                    return;
                }
                mPresenter.startSharePoster(bitmap, mLoadMoreListener.fetchPosterInfoWithPosition(mCurPosition), categoryCode, source);
                break;

            case R.id.iv_download:
                //从后台回来后有可能bitmap被回收
                if (bitmap == null || bitmap.isRecycled()) {
                    loadDataWithPosition(mCurPosition);
                    return;
                }
                PosterInfo info = mLoadMoreListener.fetchPosterInfoWithPosition(mCurPosition);

                String fromAndType = categoryCode == PosterContainerFragment.DataType.PRODUCT_POSTER ? EventID.FROM_POSTER_PRODUCT :
                        (categoryCode == PosterContainerFragment.DataType.INFORMATION_POSTER ? EventID.FROM_POSTER_INFORMATION : EventID.FROM_POSTER_QUOTES);
                String sourceTemp = (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER && !StringUtils.isEmpty(source)) ? source : mContext.getIntent().getStringExtra(BundleKey.PARAM_POSTER_SOURCE);

                analyse(PreferenceManager.getStringData(SharePrefKeys.PREF_SHARE_ID), String.valueOf(info.templateId), fromAndType, fromAndType, sourceTemp);
                String path = Cache.getPosterImageFileDirectory() + System.currentTimeMillis() + ".png";
                FileUtils.writeImage(bitmap, path, 100);
                AndroidUtils.scanFile(mContext, path);
                ToastUtils.toastMessage(mContext, "图片已保存到图库");
                break;

            case R.id.iv_close:
                dismissSelf();
                break;

            case R.id.rl_root:
                dismissSelf();
                break;
            case R.id.iv_more:
                Router.create(getContext(), RouterConstants.getNativeRouter(RouterConstants.POSTER_LIST))
                        .addParam(BundleKey.TYPE, categoryCode == PosterContainerFragment.DataType.JINJU_POSTER ? PosterListActivity.ROUTER_TYPE_JINJU : PosterListActivity.ROUTER_TYPE_POSTER)
                        .open();
                break;
        }
    }

    @EventTrace(EventID.APP_POSTER_DETAIL_DOWNLOAD)
    private void analyse(@EventTraceParam(EventDataField.ParamPostion) String position, @EventTraceParam(EventDataField.ParamId) String id,
                         @EventTraceParam(EventDataField.ParamFrom) String from, @EventTraceParam(EventDataField.ParamType) String type,
                         @EventTraceParam(EventDataField.ParamSource) String source) {
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstComeIn) {
            isFirstComeIn = false;
            return;
        }
        if (bitmap == null || bitmap.isRecycled()) {
            bitmap = null;
            setBtnStatus(false);
            loadDataWithPosition(mCurPosition);
        }
    }

    public void onLoadPositionDataSuccess(int position, PosterInfo info, boolean refresh) {
        if (info != null && position == mCurPosition) {
            mPresenter.startLoadPoster(info, mCurPosition, refresh);
            analyTabHelper.setToAndSend(position, info);
        }
        analyTabHelper.reset();
    }

    public void onLoadPositionDataFail(int position) {
        loadFail(position);
    }

    private void setBtnStatus(boolean enable) {
        ivShare.setEnabled(enable);
        ivShare.setAlpha(enable ? 1.0f : 0.4f);
        ivDownload.setEnabled(enable);
        ivDownload.setAlpha(enable ? 1.0f : 0.4f);
    }

    private void setPositionView() {
        tvPosition.setText((mCurPosition + 1) + "/" + mTotal);
    }


    private void setNavView() {
        if (mTotal == 1) {
            ivPrevious.setVisibility(View.GONE);
            ivNext.setVisibility(View.GONE);
        } else if (mCurPosition == 0) {
            ivPrevious.setVisibility(View.GONE);
            ivNext.setVisibility(View.VISIBLE);
        } else if (mCurPosition == mTotal - 1) {
            ivPrevious.setVisibility(View.VISIBLE);
            ivNext.setVisibility(View.GONE);
        } else {
            ivPrevious.setVisibility(View.VISIBLE);
            ivNext.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageSelected(int position) {
        String analayId = null;
        PosterInfo preInfo = null;
        if (!isFirstDisplay && mLastPosition >= 0 && position != mLastPosition) {
            analayId = position > mLastPosition ? "right" : "left";
            preInfo = mLoadMoreListener.fetchPosterInfoWithPosition(mLastPosition);
        }

        mCurPosition = position;
        mLastPosition = mCurPosition;
        setPositionView();
        setNavView();
        shouldRefresh = false;
        loadDataWithPosition(position);

        if (analayId != null && preInfo != null) {
            PosterInfo info = mLoadMoreListener.fetchPosterInfoWithPosition(position);
            String type = categoryCode == PosterContainerFragment.DataType.JINJU_POSTER ? "app_quotes_read" : "app-poster";
            if (info != null) {
                analyTab(analayId, preInfo.templateId, info.templateId, type);
            } else {
                analyTabHelper.waitToSent(analayId, preInfo.templateId, type, position);
            }
        }
    }

    @EventTrace(EventID.APP_POSTER_DETAIL_TAB)
    public void analyTab(@EventTraceParam(EventDataField.ParamId) String leftOrRight, @EventTraceParam(EventDataField.ParamFrom) int form, @EventTraceParam(EventDataField.ParamTo) int to, @EventTraceParam(EventDataField.ParamType) String type) {

    }

    private void loadDataWithPosition(int position) {
        if (mLoadMoreListener == null) return;
        PosterInfo info = mLoadMoreListener.fetchPosterInfoWithPosition(position);
        if (info == null) {
            int page = position / PosterPresenter.LIMIT + 1;
            mLoadMoreListener.reqLoadPage(page);
        } else {
            mPresenter.startLoadPoster(info, mCurPosition, shouldRefresh);
        }
    }

    private void initStyle() {

        if (style == Style.Normal) {//海报详情
            int dp15 = dp(mContext, 15);
            int dp45 = dp(mContext, 45);
            ((ViewGroup.MarginLayoutParams) tvPosition.getLayoutParams()).topMargin = dp15;
            ViewGroup.MarginLayoutParams btnsLp = (ViewGroup.MarginLayoutParams) llActionBtns.getLayoutParams();
            btnsLp.topMargin = dp15;
            btnsLp.bottomMargin = dp45;
            llActionBtns.setLayoutParams(btnsLp);

            int middleBlack = ContextCompat.getColor(mContext, R.color.text_middle_black);
            tvRefresh.setTextColor(middleBlack);
            tvDownload.setTextColor(middleBlack);
            tvShare.setTextColor(middleBlack);
            llClose.setVisibility(View.GONE);
            llMore.setVisibility(View.VISIBLE);
            tvPosition.setTextColor(middleBlack);
            ivPrevious.setImageResource(R.drawable.button_leftswitch_black);
            ivNext.setImageResource(R.drawable.button_rightswitch_black);

            int px25 = dp(getContext(), 25);
            int px95 = dp(getContext(), 95);
            llFailTips.setPadding(0, px25, 0, px25);
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) llFailTips.getLayoutParams();
            lp.leftMargin = px95;
            lp.rightMargin = px95;
            llFailTips.setLayoutParams(lp);

        } else if (style == Style.Dialog) {//对话框海报列表
            llMore.setVisibility(View.GONE);
            AnimatorSet set = new AnimatorSet();
            ObjectAnimator anX = ObjectAnimator.ofFloat(rlPosterContainer, "scaleX", 0, 1);
            ObjectAnimator anY = ObjectAnimator.ofFloat(rlPosterContainer, "scaleY", 0, 1);
            set.setDuration(500);
            set.play(anX).with(anY);
            set.start();
        }
    }

    private class MyAdapter extends CyclePagerAdapter<Integer> {
        public void setCurrentViewBitmap(final int realPosition, final Bitmap bm) {
            vpPosters.post(new Runnable() {
                @Override
                public void run() {
                    View iv = vpPosters.getViewPager().findViewWithTag(realPosition);
                    if (iv instanceof FrescoImageView && bm != null && !bm.isRecycled()) {
                        ((FrescoImageView) iv).setImageBitmap(bm);
                    }
                }
            });

        }

        public void loadDefaultView(final int position, final String url) {
            vpPosters.post(new Runnable() {
                @Override
                public void run() {
                    View iv = vpPosters.getViewPager().findViewWithTag(position);
                    if (iv != null && iv instanceof FrescoImageView) {
                        ((FrescoImageView) iv).loadView(url);
                    }
                }
            });

        }

        @Override
        public View getView(ViewGroup container, int position) {
            RelativeLayout rlContainer = new RelativeLayout(getContext());
            rlContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            FrescoImageView ivItem = new FrescoImageView(getContext());
            RelativeLayout.LayoutParams lp;
            if (categoryCode == PosterContainerFragment.DataType.JINJU_POSTER) {
                ivItem.setAspectRatio(1.0f);
                ivItem.setPlaceholderImage(ContextCompat.getDrawable(getContext(), R.drawable.logo), ScalingUtils.ScaleType.FIT_START);
                if (style == Style.Dialog) {
                    ivItem.setActualImageScaleType(ScalingUtils.ScaleType.FIT_START);
                    ivItem.setScaleType(ImageView.ScaleType.FIT_START);
                    int dp109 = UIUtil.dp(getActivity(), 109);
                    int dp43 = UIUtil.dp(getActivity(), 43);
                    ivItem.setPadding(dp43, dp109, dp43, 0);
                    lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);

                } else {
                    ivItem.setActualImageScaleType(ScalingUtils.ScaleType.FIT_START);
                    ivItem.setScaleType(ImageView.ScaleType.FIT_START);
                    int dp43 = UIUtil.dp(getActivity(), 43);
                    ivItem.setPadding(dp43, 0, dp43, 0);
                    lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }

            } else {
                ivItem.setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
                ivItem.setAspectRatio(0.5625f);
                ivItem.setPlaceholderImage(ContextCompat.getDrawable(getContext(), R.drawable.logo), ScalingUtils.ScaleType.CENTER_CROP);
                lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
            }
            ivItem.setTag(position);
            if (style == Style.Normal) {
                ivItem.setBorder(ContextCompat.getColor(getContext(), R.color.white), dp(getContext(), 1));
            }
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            rlContainer.addView(ivItem, lp);
            rlContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissSelf();
                }
            });
            return rlContainer;
        }

    }

    public ViewPager getVpPoster() {
        return vpPosters.getViewPager();
    }

    public CheckBox getDisplayMarkView() {
        return cbDisplayMark;
    }

    @Override
    public void onDestroy() {
        if (mPresenter != null) {
            mPresenter.onDestroy();
            mPresenter = null;
        }
        super.onDestroy();
    }

    public class AnalyTabHelper {
        private String leftOrRight;
        private int form;
        private int to;
        private String type;

        private int position;
        public void run() {
            if (!TextUtils.isEmpty(leftOrRight) && form > 0 && to > 0 && !TextUtils.isEmpty(type)) {
                analyTab(leftOrRight, form, to, type);
            }
        }

        public void waitToSent(String leftOrRight, int form, String type, int position) {
            this.leftOrRight = leftOrRight;
            this.form = form;
            this.type = type;
            this.position = position;
        }

        public void setToAndSend(int position, PosterInfo infoTo) {
            if (this.position == position) {
                to = infoTo.templateId;
                run();
            }
            reset();
        }

        public void reset() {
            leftOrRight = null;
            form = 0;
            to = 0;
            type = null;
            position = -1;
        }
    }
}
